import { useState, useEffect, useRef, useMemo, useCallback } from 'react'
import { ImgFrameSty } from './style';
import React from 'react';

//枚举图片填充方式
enum ObjectFit {
  contain = 'contain',
  cover = 'cover',
  fill = 'fill',
  none = 'none',
  scaleDown = 'scale-down',
}

interface LazyImgProps {
  src: string,
  alt?: string,
  isLazy?: boolean
  style?: React.CSSProperties,
  /** 加载完毕*/
  finishedLoading?: (imgDom: React.ReactNode) => void,
  objectfit?: ObjectFit
}

export default function LazyImg(props: LazyImgProps) {
  const { src, alt = "", isLazy = false, style = {}, finishedLoading = () => { }, objectfit = ObjectFit.cover } = props
  const imgDom = useRef<any>(null);
  const [isFinishLoad, setIsFinishLoad] = useState(false)

  useEffect(() => {
    if (imgDom.current === null || !isFinishLoad ) {
      return
    }
    finishedLoading(imgDom.current)
  }, [isFinishLoad])

  useEffect(() => {
    if (imgDom.current === null || src === '') {
      return
    }
    if (!isLazy) {
      imgDom.current.src = src
      imgDom.current.onload = () => {
        setIsFinishLoad(true)
      }
      return
    }
    const observer = new IntersectionObserver((entries, observer) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {   
          imgDom.current.src = src;
          imgDom.current.onload = () => {
            setIsFinishLoad(true)
          }
          //使 IntersectionObserver 停止监听特定目标元素。
          observer.unobserve(imgDom.current);
        } else {
          // console.log('元素离开视口');
        }
      });
    });
    observer.observe(imgDom.current);

    return () => {
      observer.disconnect();
    }
  }, [src])

  return (
    <ImgFrameSty style={style} objectfit={objectfit}>
      <img ref={imgDom} alt={alt} />
    </ImgFrameSty>
  )
}